package HTML::FormFu::Validator::DBIC::Model;

use strict;
use warnings;
use base 'HTML::FormFu::Validator';

__PACKAGE__->mk_accessors( qw/
    load_params_from_request
    model
    match_params
    max_found
    negative_match_params
/ );


sub validate_value {
    my ( $self, $value, $params ) = @_;
    my $model;
    my $i = 0;
    my $argument_params = {};
    my $resultset;
    my $match = {};
    my $max = $self->max_found || 0;
    my $ok;

    return 1 if !defined $value || $value eq '';

    # check model name
    $self->model
        or die "Model not named - Need model name for DB check.";

    # check Catalyst context
    $self->form->{stash}->{context}
        or die "Catalyst context not available.";

    # check for valid model
    $model = $self->form->{stash}->{context}->model( $self->model )
        or die "Model not defined - DB check failed for model '". $self->model. "'.";

    # get parameters from request
    foreach my $param (@{$self->load_params_from_request || []}) {
        $argument_params->{$param} = $self->form->{stash}->{context}->request->arguments->[$i];
        $i++;
    }

    # prepare hash for search operation in model
    foreach my $param (@{$self->match_params || []}) {
        $match->{$param} = $params->{$param}
            if exists $params->{$param};
        $match->{$param} = $argument_params->{$param}
            if exists $argument_params->{$param};
    }
    foreach my $param (@{$self->negative_match_params || []}) {
        $match->{$param} = { '!=', $params->{$param} }
            if exists $params->{$param};
        $match->{$param} = { '!=', $argument_params->{$param} }
            if exists $argument_params->{$param};
    }

    # create resultset
    $resultset = $model->search( $match )
        or die "No resultset defined - DB check failed for model '". $self->model. "'.";

    # validate
    $ok = $resultset->count <= $max;

    return $ok;
}

1;

__END__

=head1 NAME

glue::HTML::FormFu::Validator::DBIxClassModel - Validator for constraints in DBIx::Class catalyst model

=head1 SYNOPSIS

validator:
  - type: +glue::HTML::FormFu::Validator::DBIxClassModel
    name: name
    model: 'glueDB::Contact::Company'
    match_params: [ name ]
    negative_match_params: [ id ]
    load_params_from_request: [ id ]
    max_found: 0

=head1 DESCRIPTION

Checks a defineable constraint (e.g. unique constraint on a specific field).

Is a sub-class of, and inherits methods from L<HTML::FormFu::Validator>

L<HTML::FormFu::FormFu>

=head1 AUTHOR

Mario Minati C<mario.minati@googlemail.com>


=head1 LICENSE

This library is free software, you can redistribute it and/or modify it under
the same terms as Perl itself.
